﻿using System.Diagnostics;
using System.Net.Sockets;
using System.Text;

namespace WemoConnect1
{
    public abstract class WemoCommand
    {
        protected Socket WemoSocket;

        public void Execute(Socket socket)
        {
            WemoSocket = socket;
            Execute();
        }

        protected abstract void Execute();

        protected void SendRequest(string request)
        {
            var count = WemoSocket.Send(Encoding.UTF8.GetBytes(request));
            Debug.WriteLine("\n\n--------------------->");
            Debug.WriteLine(request);
            Debug.WriteLine("--------------------->");
        }

        protected void SendRequest(byte[] request, int length)
        {
            var count = WemoSocket.Send(request, length, SocketFlags.None);
            Debug.WriteLine("--------------------->");
            Debug.WriteLine(request);
            Debug.WriteLine("--------------------->");
        }

        protected void ReceiveRequestState()
        {
            var buffer = new byte[51200];
            var countReceived = WemoSocket.Receive(buffer);
            while (countReceived == 0)
            {
                countReceived = WemoSocket.Receive(buffer);
            }

            var response = Encoding.UTF8.GetString(buffer, 0, countReceived);
            Debug.WriteLine("<---------------------");
            Debug.WriteLine(response);
            Debug.WriteLine("<---------------------");
        }

        protected void ReceiveResponse()
        {
            ReceiveRequestState();
        }
    }
}
